import axios, { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from "axios";
import Nprogress from "nprogress";
import { getToken } from "@/utils/cookie.ts";

const request: AxiosInstance = axios.create({
  baseURL: "/api",
  timeout: 10000,
});

request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  Nprogress.start();
  const token: string = getToken();
  if (token) {
    config.headers.token = token;
  }
  return config;
}, (error: AxiosError) => {
  return Promise.reject(error);
});

request.interceptors.response.use((response: AxiosResponse) => {
  Nprogress.done();
  if (response.data && response.data.code !== 200) {
    return Promise.reject(new Error(response.data.message));
  }
  return response.data;
}, (error: AxiosError) => {
  Nprogress.done();
  return Promise.reject(error);
});

export default request;
